#!/bin/bash

ARG=${1}
echo "ARG=${ARG}"

TAG=${2-'latest'}
IMG_NAME=supreme-study-server

build_image() {
  # image build
  docker build \
    --build-arg JAR_FILE=./target/${IMG_NAME}-0.0.1.jar \
    --platform linux/amd64 \
    --no-cache \
    -t supreme/${IMG_NAME}:${TAG} \
    -f ./Dockerfile .
}

run_image() {
  local HOST_PATH="${HOME}/Development/docker-data/supreme-server/${IMG_NAME}"
  echo "HOST_PATH=${HOST_PATH}"
  docker run \
    --rm \
    --platform linux/amd64 \
    --name ${IMG_NAME} \
    -p 7230:7230 \
    -p 7231:7231 \
    -v ${HOST_PATH}/logs:/home/${IMG_NAME}/logs \
    -d supreme/${IMG_NAME}:${TAG}

  docker logs -f ${IMG_NAME}
}

stop_ctn() {
  local CTN_ID=`docker ps -q -f name=${IMG_NAME}`
  if [ -n "${CTN_ID}" ]; then
      docker stop ${CTN_ID}
  fi
}

remove_image() {
  local IMG_ID=`docker images -f label="name=${IMG_NAME}" -q`
  if [ -n "${IMG_ID}" ]; then
    docker rmi ${IMG_ID}
  fi
}

show_image() {
  docker images -f label="name=${IMG_NAME}"
}

if [ -z "$ARG" ]; then
    echo "[ build | run | stop | clear | logs | tag | push | package ]"
    exit 1
fi

if [ "$ARG" == "build" ]; then
  remove_image
  build_image
  show_image
elif [ "$ARG" == "run" ]; then
  stop_ctn
  run_image
elif [ "$ARG" == "stop" ]; then
  stop_ctn
elif [ "$ARG" == "clear" ]; then
  stop_ctn
  remove_image
elif [ "$ARG" == "logs" ]; then
  docker logs -f $CONTAINER_NAME
elif [ "$ARG" == "tag" ]; then
  docker tag ${IMG_NAME}:${TAG} supreme/${IMG_NAME}:${TAG}
elif [ "$ARG" == "push" ]; then
  docker push supreme/${IMG_NAME}:${TAG}
elif [ "$ARG" == "package" ]; then
  mvn -Dmaven.test.skip -U clean package
fi
